package com.poly.common.core.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.poly.common.core.tools.utils.Func;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ConvertUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public ConvertUtils() {
    }

    public static <T> T convert(Object obj, Class<T> clazz) {
        if (obj != null && clazz != null) {
            try {
                String json = MAPPER.writeValueAsString(obj);
                return MAPPER.readValue(json, clazz);
            } catch (JsonProcessingException var3) {
                var3.printStackTrace();
                throw new RuntimeException("object convert exception");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return null;
        }
        return null;
    }

    public static <T> List<T> convert(List<?> objList, Class<T> clazz) {
        List<T> list = new ArrayList();
        if (Func.isNotEmpty(objList)) {
            Iterator var3 = objList.iterator();
            while (var3.hasNext()) {
                Object obj = var3.next();
                list.add(convert(obj, clazz));
            }
        }
        return list;
    }

    public static Integer toInteger(Object val, Integer defaultValue) {
        Integer iValue = defaultValue;
        if (val != null) {
            try {
                iValue = Integer.parseInt(val.toString());
            } catch (Exception e) {
            }
        }

        return iValue;
    }


    public static BigDecimal toBigDecimal(Object val, BigDecimal defaultValue) {
        try {
            if (val != null) {
                if (val instanceof BigDecimal) {
                    return (BigDecimal) val;
                } else if (val instanceof String) {
                    return new BigDecimal((String) val);
                } else if (val instanceof BigInteger) {
                    return new BigDecimal((BigInteger) val);
                } else if (val instanceof Number) {
                    return new BigDecimal(((Number) val).doubleValue());
                }
            }
        } catch (Exception e) {
        }
        return defaultValue;
    }

    public static BigDecimal bigDecimalIsNull(BigDecimal val, BigDecimal defaultValue) {
        if (val == null) {
            return defaultValue;
        }
        return val;
    }

    public static BigDecimal bigDecimalIsNullZero(BigDecimal val) {
        if (val == null) {
            return new BigDecimal(0);
        }
        return val;
    }

    /**
     * 小于0时
     *
     * @param val
     * @return
     */
    public static BigDecimal bigDecimalMax(BigDecimal val, BigDecimal val2) {
        if (val != null && val2 != null) {
            if (val.compareTo(val2) < 0) {
                return val2;
            }
            return val;
        }
        return null;
    }

    public static BigDecimal bigDecimalIsNullOne(BigDecimal val) {
        if (val == null) {
            return new BigDecimal(1);
        }
        return val;
    }

    public static Double bigDecimalToDouble(BigDecimal val, Double defaultValue) {
        if (val == null) {
            return 0D;
        }
        return val.doubleValue();
    }

    public static Short toShort(Object val) {
        short value = 0;
        if (val != null) {
            try {
                value = Short.parseShort(val.toString());
            } catch (Exception e) {
            }
        }

        return value;
    }

    public static Short toShort(Object val, Short defaultValue) {
        try {
            if (val == null)
                return defaultValue;
            return Short.parseShort(val.toString());
        } catch (Exception e) {
        }
        return defaultValue;
    }

    public static Double toDouble(Object val, Double defaultValue) {
        try {
            if (val == null)
                return defaultValue;
            return Double.parseDouble(val.toString());
        } catch (Exception e) {
        }
        return defaultValue;
    }

    public static Long toLong(Object val, Long defaultValue) {
        try {
            if (val == null)
                return defaultValue;
            return Long.parseLong(val.toString());
        } catch (Exception e) {
        }
        return defaultValue;
    }

    public static Timestamp toTimestamp(Object val, Timestamp defaultValue) {
        try {
            if (DateTimeUtil.isValid(val.toString(), "yyyy-MM-dd HH:mm:ss")) {
                return DateTimeUtil.dataTimeToTimestamp(DateTimeUtil.stringToDateTime(val.toString(), "yyyy-MM-dd HH:mm:ss"));
            }
            return defaultValue;
        } catch (Exception e) {
        }
        return defaultValue;
    }


    public static float toFloat(Object obj, Float defaultValue) {
        Float rValue = defaultValue;
        if (obj != null) {
            try {
                rValue = Float.parseFloat(obj.toString());
            } catch (Exception ex) {

            }
        }
        return rValue;
    }


    public static String toString(Object val, String defaultValue) {
        try {
            return val.toString();
        } catch (Exception e) {
        }
        return defaultValue;
    }

    /**
     * 将字符串数组转换为以“,”分隔的字符串
     *
     * @param stringArray -要转换的字符串数组
     * @return
     */
    public static String toString(String[] stringArray) {
        return toString(stringArray, ",");
    }

    /**
     * 将字符串数组转换为以指定分隔符分隔的字符串
     *
     * @param stringArray --要转换的字符串数组
     * @param separator   --分隔符
     * @return
     */
    public static String toString(String[] stringArray, String separator) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < stringArray.length; i++) {
            if (i > 0)
                sb.append(separator);
            sb.append(stringArray[i]);
        }
        return sb.toString();
    }

    /**
     * 将字符串数组转换为以指定分隔符分隔的字符串
     *
     * @param stringArray --要转换的字符串数组
     * @param separator   --分隔符
     * @return
     */
    public static String toStringNotEmpty(String[] stringArray, String separator) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < stringArray.length; i++) {
            if (Func.isEmpty(stringArray[i].trim()))
                continue;
            if (i > 0)
                sb.append(separator);
            sb.append(stringArray[i]);
        }
        return sb.toString();
    }

    /**
     * 将泛型数组转换为以“,”分隔的字符串
     *
     * @param array -要转换的泛型数组
     * @return
     */
    public static <T> String toString(Object array) {
        return toString(array, ",");
    }

    /**
     * 将泛型数组转换为以指定分隔符分隔的字符串
     *
     * @param array     -要转换的泛型数组
     * @param separator --分隔符
     * @return
     */
    public static <T> String toString(List<T> array, String separator) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.size(); i++) {
            if (i > 0)
                sb.append(separator);
            sb.append(String.valueOf(array.get(i)));
        }
        return sb.toString();
    }

    /***
     * 使用分隔符将数组转化为字符串（泛型）
     * @param <T>
     * @param t1
     * @param separator
     * @return
     */
    public static <T> String toString(T[] t1, String separator) {
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < t1.length; i++) {
            if (i > 0) str.append(separator);
            str.append(t1[i].toString());
        }
        return str.toString();
    }

    /***
     * 使用“,”将数组转化为字符串（泛型）
     * @param <T>
     * @param t1
     * @return
     */
    public static <T> String toString(T[] t1) {
        return toString(t1, ",");
    }

    /**
     * 将字符串转移为ASCII码
     *
     * @param cnStr
     * @return
     */
    public static String toASCII(String cnStr) {
        StringBuffer strBuf = new StringBuffer();
        byte[] bGBK = cnStr.getBytes();
        for (int i = 0; i < bGBK.length; i++) {
            strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
        }
        return strBuf.toString();
    }

    public static boolean canSerialize(@Nullable Object value) {
        return value == null || MAPPER.canSerialize(value.getClass());
    }

    /**
     * 驼峰式命名法
     */
    public static String toCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = s.toLowerCase();
        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == '_') {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.registerModule(new JavaTimeModule());
    }
}
